package com.ta.gulimall.coupon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ta.gulimall.coupon.view.vo.SeckillSkuVo;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ta.gulimall.common.utils.system.PageUtils;
import com.ta.gulimall.common.utils.system.Query;

import com.ta.gulimall.coupon.dao.SeckillSkuRelationDao;
import com.ta.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.ta.gulimall.coupon.service.SeckillSkuRelationService;


@Service("seckillSkuRelationService")
public class SeckillSkuRelationServiceImpl extends ServiceImpl<SeckillSkuRelationDao, SeckillSkuRelationEntity> implements SeckillSkuRelationService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSkuRelationEntity> page = this.page(
                new Query<SeckillSkuRelationEntity>().getPage(params),
                new QueryWrapper<SeckillSkuRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Map<Long, List<SeckillSkuVo>> querySessionGoods(List<Long> sessionIds) {
        LambdaQueryWrapper<SeckillSkuRelationEntity> wrapper = new LambdaQueryWrapper<SeckillSkuRelationEntity>()
                .in(SeckillSkuRelationEntity::getPromotionSessionId, sessionIds)
                .eq(SeckillSkuRelationEntity::getSeckillSort, 0);
        List<SeckillSkuRelationEntity> seckillSkuRelationList = list(wrapper);

        Map<Long, List<SeckillSkuVo>> seckillSkuMap = seckillSkuRelationList.stream().collect(Collectors.groupingBy(
                SeckillSkuRelationEntity::getPromotionSessionId,
                Collectors.mapping(seckillSku -> BeanUtil.copyProperties(seckillSku, SeckillSkuVo.class), Collectors.toList())
        ));

        List<Long> skuIds = seckillSkuRelationList.stream().map(SeckillSkuRelationEntity::getId).collect(Collectors.toList());
        updateSeckillSkuStatus(skuIds);
        return seckillSkuMap;
    }

    //修改商品上架状态
    private void updateSeckillSkuStatus(List<Long> skuIds) {
        List<SeckillSkuRelationEntity> seckillSkuRelationList = skuIds.stream().map(skuId -> {
            return SeckillSkuRelationEntity.builder()
                    .id(skuId)
                    .seckillSort(1)
                    .build();
        }).collect(Collectors.toList());
        updateBatchById(seckillSkuRelationList);
    }

}